import logging
import time


def ease_out_cubic(t):
    # 缓动函数 - 先快后慢
    return 1 - (1 - t) ** 3


def move_with_easing(page, end_x, end_y, duration):
    start_time = time.time()
    numbers_x = [0]
    numbers_y = [0]
    while True:
        elapsed_time = time.time() - start_time
        if elapsed_time >= duration:
            # 动画结束
            break
        # 计算当前时间对应的缓动值
        t = elapsed_time / duration
        easing_value = ease_out_cubic(t)
        # 根据缓动值计算当前位置
        current_x = end_x * easing_value
        current_y = end_y * easing_value
        num_x = round(current_x - numbers_x[-1], 1)
        num_y = round(current_y - numbers_y[-1], 1)
        page.actions.move(num_x, num_y, 0)
        numbers_x.append(current_x)
        numbers_y.append(current_y)


def 滑块验证码(page, x):
    count = 0
    if page.eles('#nocaptcha'):
        while page('#nocaptcha').states.is_displayed:
            logging.info('出现滑块验证码')
            if count == 3:
                page.quit()
                raise Exception('滑块验证码超过3次验证失败')
            btn_slide_eles = page.eles('.nc_iconfont btn_slide')
            if len(btn_slide_eles) == 2:
                btn_slide = btn_slide_eles[1]
            else:
                btn_slide = btn_slide_eles[0]
            page.actions.hold(btn_slide)
            move_with_easing(page, x, 15, 3)
            page.wait(3)
            if page('#nocaptcha').states.is_displayed:
                count += 1
                logging.info('滑块验证码验证失败')
                page('#nocaptcha', timeout=1).ele('.errloading', timeout=1).click()
                page.wait(1)
        logging.info('滑块验证码消失')
